package com.shenyuan.module_basekt.api.fastjson

import com.alibaba.fastjson.JSONWriter
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.Buffer
import retrofit2.Converter
import java.io.OutputStreamWriter
import java.nio.charset.StandardCharsets

/**
 * @author ch
 * @date 2022/7/15-14:23
 * desc
 */
class FastJsonRequestBodyConverter<T> : Converter<T, RequestBody> {

    val MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8")
    val UTF_8 = StandardCharsets.UTF_8;

    override fun convert(value: T): RequestBody? {
        val buffer = Buffer()
        val writer = OutputStreamWriter(buffer.outputStream(), UTF_8)
        val jsonWriter = JSONWriter(writer)
        jsonWriter.writeValue(value)
        jsonWriter.close()
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString())
    }
}